import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon, Permission } from "pao-aop";
import { Row, Col, Pagination, Descriptions, Modal, Button, message } from "antd";
import './index.less';
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
import { request } from "src/business/util_tool";
import Search from "antd/lib/input/Search";

/**
 * 组件：慈善拨款页状态
 */
export interface ChangeCharitableAppropriationState extends ReactViewState {
    /** 页面列表数据 */
    data_list?: any;
    /** 当前页数 */
    current: number;
    /** 一页展示多少条数据 */
    pagesize: number;
    /** 接口名 */
    request_url?: string;
    total?: number;
    // 弹窗是否显示
    modal_visible: boolean;
    // 判断是否存在的
    alert_modal_visible: boolean;
    // 当前查看的
    donate_info: any;
    // 当前关键字
    intention: string;
    // 搜索框的内容
    input_value: string;
    // 选择的数组
    selected_ids: string[];
    // 选择的金额
    selected_money: number;
    // 来源募捐项目
    apply_info: any[];
    // 已存在的募捐审核申请
    exists_apply_id: string;
}

/**
 * 组件：慈善拨款页
 */
export class ChangeCharitableAppropriation extends ReactView<ChangeCharitableAppropriationViewControl, ChangeCharitableAppropriationState> {
    constructor(props: any) {
        super(props);
        this.state = {
            data_list: [],
            current: 1,
            pagesize: 50,
            total: 0,
            request_url: '',
            modal_visible: false,
            alert_modal_visible: false,
            donate_info: [],
            intention: '',
            input_value: '',
            selected_ids: [],
            selected_money: 0,
            apply_info: [],
            exists_apply_id: '',
        };
    }
    onChange = (page: number, pagesize: number) => {
        this.selectdata(page, pagesize, this.state.intention);
    }
    onShowSizeChange = (current: number, pagesize: number) => {
        this.selectdata(current, pagesize, this.state.intention);
    }
    componentWillMount() {
        let request_url = this.props.request_url;
        this.setState({
            request_url
        });
    }
    componentDidMount() {
        request(this, AppServiceUtility.charitable_service.get_charitable_recipient_apply_list_all!({ id: this.props.match!.params.key }, 1, 1))
            .then((datas: any) => {
                if (!datas.result && !datas.result[0]) {
                    message.error('数据出错，请联系管理员！');
                    return;
                }
                // let apply_info = datas.result[0] || [];

                // 已经有申请了，就跳过去
                if (datas.result && datas.result[0] && datas.result[0]['step_no'] === 2 && datas.result[0]['donate_ids'].length > 0) {
                    this.props.history!.push(ROUTE_PATH.recipientApply + '/' + datas.result[0]['id']);
                    return;
                }
                this.setState(
                    {
                        apply_info: datas.result[0],
                    },
                    () => {
                        this.selectdata(this.state.current, this.state.pagesize, '');
                    }
                );
            });

    }
    // 搜索操作封装
    selectdata = (current: number, pagesize: number, intention: string) => {
        current = current || this.state.current;
        pagesize = pagesize || this.state.pagesize;
        intention = intention || this.state.intention;
        let param: any = intention ? { intention: intention } : {};
        param.donate_type = '';
        request(this, AppServiceUtility.charitable_service.get_charitable_donate_list_all!(param, 1, 99))
            .then((datas: any) => {
                this.setState({
                    selected_ids: [],
                    selected_money: 0,
                    data_list: datas.result,
                });
            });
    }
    // 搜索操作
    searchList(value: any) {
        this.setState(
            {
                intention: value,
                input_value: value,
                selected_ids: [],
                selected_money: 0,
            },
            () => {
                this.selectdata(this.state.current, this.state.pagesize, value);
            }
        );
    }
    // 判断元素是否在数组里，id为判断基准
    inArray(id: string, array: any) {
        for (let i in array) {
            if (array[i]) {
                if (array[i]['id'] === id) {
                    return true;
                }
            }
        }
        return false;
    }
    // 选择和取消选择的操作
    chooseThis(e: any, item: any) {
        let { selected_ids, selected_money, apply_info } = this.state;
        let apply_money = apply_info['apply_money'];
        if (this.inArray(item.id, selected_ids)) {
            // 已选择，是取消操作
            let new_ids: string[] = [];
            let new_money: number = 0;
            for (let i in selected_ids) {
                if (selected_ids[i]) {
                    if (selected_ids[i]['id'] !== item.id) {
                        // 重新赋值操作
                        let result = this.pipeiCore(new_money, selected_ids[i], apply_money);
                        new_ids.push(result['item']);
                        new_money = result['selected_money'];
                    }
                }
            }
            selected_ids = new_ids;
            selected_money = new_money;
        } else {
            // 新选择的

            // 判断是否选择足够了
            if (selected_money > apply_money) {
                // 不可能选择超过的
                message.error('数据出错，请刷新重试！');
                return;
            } else if (selected_money === apply_money) {
                message.info('已超出所需金额！');
                return;
            }

            let result = this.pipeiCore(selected_money, item, apply_money);
            selected_ids.push(result['item']);
            selected_money = result['selected_money'];
        }
        this.setState({
            selected_ids,
            selected_money,
        });
    }
    // 匹配的核心操作
    pipeiCore(selected_money: any, item: any, apply_money: any) {
        if (selected_money + item.surplus_money <= apply_money) {
            // 这是已经占用的金额，做个标识
            item['occupy_money'] = item.surplus_money;
            // 如果已选的+剩余的小于等于所需，直接push
            selected_money += item.surplus_money;
        } else {
            // 这是已经占用的金额，做个标识
            item['occupy_money'] = apply_money - selected_money;
            // 所选的加上新选的超过了，也是直接push，但是金额直接等于所需金额
            selected_money = apply_money;
        }
        return {
            item,
            selected_money,
        };
    }
    // 跳转到审核列表
    toCharitableAppropriationList() {
        this.props.history!.push(ROUTE_PATH.recipientApply + '/' + this.state.apply_info['id']);
    }
    // 提交审核并跳转到审核列表
    submit() {
        let { selected_ids, selected_money, apply_info } = this.state;
        if (selected_ids.length < 1) {
            message.error('请选择捐款！');
            return;
        }
        if (selected_money < apply_info['apply_money']) {
            message.error('所选捐款金额不足！');
            return;
        }
        let select_id_array: any = [];
        selected_ids.map((item: any, index) => {
            select_id_array.push({
                id: item.id,
                occupy_money: item.occupy_money,
            });
        });
        let that = this;
        // 个人在第一，机构在第三
        let step_no = apply_info['apply_type'] === '个人' ? 1 : 3;
        request(this, AppServiceUtility.charitable_service.update_charitable_recipient_apply!({ status: '待审批', sp_status: '通过', is_sp: 1, step_no: step_no, id: apply_info['id'], donate_ids: select_id_array, apply_type: apply_info['apply_type'] }))
            .then((data: any) => {
                if (data === 'Success') {
                    message.success('操作成功！', 3, () => that.toCharitableAppropriationList());
                } else if (typeof (data) === 'object') {
                    if (data.msg === 'isApplying') {
                        this.setState({
                            alert_modal_visible: true,
                            exists_apply_id: data.applyingId
                        });
                    }
                } else {
                    message.error(data);
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    // 显示模态框
    showModal() {
        this.setState({
            modal_visible: true,
        });
    }
    // 隐藏模态框
    hideModal() {
        this.setState({
            modal_visible: false,
        });
    }
    hideAlertModal() {
        this.setState({
            alert_modal_visible: false,
        });
    }
    toExistsApply() {
        this.props.history!.push(ROUTE_PATH.charitableAppropriation + '/' + this.state.exists_apply_id);
    }
    render() {
        const { donate_info, data_list, selected_ids, selected_money, apply_info } = this.state;
        return (
            <Row className="charitable-appropriation-list">
                <Modal
                    width={500}
                    visible={this.state.alert_modal_visible}
                    okText="确定"
                    cancelText="返回"
                    onOk={() => this.toExistsApply()}
                    onCancel={() => this.hideAlertModal()}
                >
                    <Row>当前募捐已有未审核申请，是否跳转到申请信息？</Row>
                </Modal>
                <Modal
                    // title="项目详情"
                    className="charitable-appropriation-modal"
                    width={1100}
                    visible={this.state.modal_visible}
                    okText="OK"
                    cancelText="返回"
                    onOk={() => this.hideModal()}
                    onCancel={() => this.hideModal()}
                    okButtonProps={{ className: 'okBtn' }}
                >
                    <Descriptions title="捐赠明细" bordered={true}>
                        <Descriptions.Item label="捐款名义">{donate_info.donate_name || ''}</Descriptions.Item>
                        <Descriptions.Item label="捐款项目">{donate_info.donate_project_name || ''}</Descriptions.Item>
                        <Descriptions.Item label="捐款金额">￥{donate_info.donate_money || ''}</Descriptions.Item>
                        <Descriptions.Item label="联系方式">{donate_info.contacts || ''}</Descriptions.Item>
                        <Descriptions.Item label="捐款时间" span={2}>{donate_info.create_date || ''}</Descriptions.Item>
                        <Descriptions.Item label="捐款留言" span={3}>{donate_info.remark || ''}</Descriptions.Item>
                    </Descriptions>
                </Modal>
                <Descriptions title="慈善拨款项目" layout="vertical" bordered={false} />
                <br />
                <Row type="flex" justify="space-between" align="middle">
                    <Col span={32}>
                        <Search
                            defaultValue={apply_info['description'] || ''}
                            placeholder="请输入捐款意向/金额"
                            enterButton="一键匹配"
                            size="large"
                            onSearch={(value) => this.searchList(value)}
                        />
                    </Col>
                    <Col>
                        &nbsp;&nbsp;&nbsp;&nbsp;募捐人：{apply_info['apply_name'] || ''}&nbsp;&nbsp;&nbsp;&nbsp;申请金额：{apply_info['apply_money'] || 0}&nbsp;&nbsp;&nbsp;&nbsp;已选择：￥{selected_money}
                    </Col>
                </Row>
                <br />
                <Row gutter={16} className="list-content">
                    {(() => {
                        if (data_list.length > 0) {
                            return data_list!.map((item: any, index: number) => {
                                let cls = this.inArray(item.id, selected_ids) === true ? 'project-section selected' : 'project-section';
                                return (
                                    <Col key={index} className="projectlist">
                                        <Row className={cls} onClick={(e) => { this.chooseThis(e, item); }}>
                                            <Row className="detail">
                                                <Row>
                                                    捐款名义：{item.donate_name || ''}
                                                </Row>
                                                <Row className="price">
                                                    捐款金额：￥<strong>{item.donate_money || 0}</strong>
                                                </Row>
                                                <Row className="price">
                                                    已使用金额：￥<strong>{item.payed_money || 0}</strong>
                                                </Row>
                                                <Row className="price">
                                                    冻结金额：￥<strong>{item.freeze_money || 0}</strong>
                                                </Row>
                                                <Row className="price">
                                                    剩余金额：￥<strong>{item.surplus_money || 0}</strong>
                                                </Row>
                                                <Row className="intention">
                                                    捐款意向：{item.donate_intention || ''}
                                                </Row>
                                            </Row>
                                        </Row>
                                    </Col>
                                );
                            });
                        } else {
                            return <Row className="empty-data">
                                <Row type="flex" justify="center">暂无数据</Row>
                            </Row>;
                        }
                    })()}
                </Row>
                {(() => {
                    if (selected_ids.length > 0) {
                        return (
                            <Row type="flex" justify="center" className="submit-row">
                                <Button onClick={() => this.submit()}>提交审核</Button>
                            </Row>
                        );
                    }
                    return null;
                })()}
                <Pagination
                    showSizeChanger={true}
                    onChange={this.onChange}
                    onShowSizeChange={this.onShowSizeChange}
                    total={this.state.total}
                    pageSize={this.state.pagesize}
                />
            </Row>
        );
    }
}

/**
 * 组件：慈善拨款页
 * 慈善拨款页
 */
@addon('ChangeCharitableAppropriation', '慈善拨款页', '慈善拨款')
@reactControl(ChangeCharitableAppropriation, true)
export class ChangeCharitableAppropriationViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
    /** 请求接口名 */
    public request_url?: string;
    /** 获取权限接口类 */
    public permission_class?: any;
    /** 获取权限接口方法名 */
    public get_permission_name?: string;
    /** 查询权限 */
    public select_permission?: string;
    /** 编辑权限 */
    public edit_permission?: string;
    /** 删除权限 */
    public delete_permission?: string;
    /** 新增权限 */
    public add_permission?: string;
}
